<?php

class m_flow extends CI_Model{
	
	function _list($data){
		extract($data);
		$sql = "SELECT 
					flow_name,
					flow_code,
					flow_subcode,
					flow_id
				FROM m_flow
				WHERE 
					flow_active = 'y'
		";
		
		if (@$flow_name != "") $sql .= " AND flow_name like '%".@$flow_name."%'";
		if (@$flow_code != "") $sql .= " AND flow_code like '%".@$flow_code."%'";
		if (@$flow_subcode != "") $sql .= " AND flow_subcode like '%".@$flow_subcode."%'";
		
		$query = $this->db->query($sql);
		$records = $query->num_rows();
		
		$sql = "SELECT * FROM (".$sql.") k LIMIT ".(($page - 1) * $rows).",".$rows;
		$query = $this->db->query($sql);
		$result = $query->result();
		
		return '{ 
		  "total": "'.ceil($records / $rows).'", 
		  "page": "'.$page.'", 
		  "records": "'.$records .'",
		  "rows" : '.json_encode($result).'
		}';
	}
	
	function _insert($data){
		$this->db->insert('m_flow',$data);
		return 1;
	}
	
	function _update($data,$id,$flowdiv_id){
		$this->db->where('flow_id',$id);
		$this->db->update('m_flow',$data);
		
		$this->db->where('m_flow_id',$id);
		$this->db->order_by('flowdet_seq');
		$query = $this->db->get('m_flowdet');
		$i = 0;
		
		foreach($query->result() as $row){
			if ($i < count($flowdiv_id)){
				$data_detail = array(
					"m_div_id" => $flowdiv_id[$i],
					
					'flowdet_update_user'	=>$_SESSION[SESSION_USERNAMA],
					'flowdet_update_date'=> date("Y-m-d h:i:s"),
					"flowdet_active" => "y"
				);
				
				$this->db->where('flowdet_id',$row->flowdet_id);
				$this->db->update('m_flowdet',$data_detail);
			}else{
				$this->db->where('flowdet_id',$row->flowdet_id);
				$this->db->update('m_flowdet',array( "flowdet_active" => "n"));
			}
			$i++;
		}
			
		while($i < count($flowdiv_id)){
			
			$data_detail = array(
				"m_div_id" => $flowdiv_id[$i],
				"flowdet_seq" => $i + 1,
				"m_flow_id" => $id,
				
				'flowdet_insert_user'	=>$_SESSION[SESSION_USERNAMA],
				'flowdet_insert_date'=> date("Y-m-d h:i:s"),
				"flowdet_active" => "y"
			);
			$this->db->insert('m_flowdet', $data_detail);
			$i++;
		}
		return 1;
	}
	
	function _delete($data,$id){
		$this->db->where('flow_id',$id);
		$this->db->update('m_flow',$data);
		return 1;
	}
}